package com.dyz.leetcode;

/**
 * @author: daiyizheng
 * @date: 2021/7/9 21:41
 * @description:
 */
public class AddTwoNumbers2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null&&l2==null){
            return l1;
        }else if(l1==null){
            return l2;
        }else if(l2==null){
            return l1;
        }
        //创建新的节点
        ListNode res = new ListNode(0);
        ListNode cur = res;
        int carry = 0;
        while (!(l1==null && l2==null&& carry==0)){
            int sum = carry;
            sum  += (l1!=null)?l1.val:0;
            sum += (l2!=null)?l2.val:0;
            carry = sum>9?1:0;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            if(l1!=null){l1= l1.next;}
            if(l2!=null){l2=l2.next;}
        }
        return res.next;
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}